package zl.ordermanager.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zl.ordermanager.dao.CustomerDao;
import zl.ordermanager.po.Tcustomer;
import zl.ordermanager.service.CustomerService;
import zl.ordermanager.vo.Customer;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.PageHelper;

@Service
public class CustomerServiceImpl implements CustomerService {

	@Autowired
	private CustomerDao customerDao;

	@Override
	public DataGrid<Customer> dataGrid(PageHelper pageHelper) {
		DataGrid<Customer> dataGrid = new DataGrid<Customer>();
		List<Customer> customerList = new ArrayList<Customer>();
		Map<String, Object> params = new HashMap<String, Object>();
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			params.put("keyword", "%%" + pageHelper.getKeywords() + "%%");
		}
		String hql = " from Tcustomer t ";
		String whereHql = whereHql(pageHelper);
		List<Tcustomer> tcustomerList = customerDao.find(hql + whereHql + orderHql(pageHelper), params,
				pageHelper.getPageNum(), pageHelper.getNumPerPage());
		if (tcustomerList != null && tcustomerList.size() > 0) {
			for (Tcustomer tcustomer : tcustomerList) {
				Customer customer = new Customer();
				BeanUtils.copyProperties(tcustomer, customer);
				customerList.add(customer);
			}
		}
		dataGrid.setList(customerList);
		dataGrid.setTotal(customerDao.count("select count(*) " + hql + whereHql, params));
		return dataGrid;
	}

	private String whereHql(PageHelper pageHelper) {
		String whereString = "";
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			whereString += "where (t.customer like :keyword ";
			whereString += " or t.customerType like :keyword ";
			whereString += " or t.address like :keyword ";
			whereString += " or t.contacts like :keyword ";
			whereString += " or t.department like :keyword ";
			whereString += " or t.job like :keyword ";
			whereString += " or t.telephone like :keyword ";
			whereString += " or t.phone like :keyword ";
			whereString += " or t.fax like :keyword ";
			whereString += " or t.otherContact like :keyword)";
		}

		return whereString;
	}

	private String orderHql(PageHelper pageHelper) {
		String orderString = "";
		if (pageHelper.getOrderField() != null && !pageHelper.getOrderField().isEmpty()
				&& pageHelper.getOrderDirection() != null && !pageHelper.getOrderDirection().isEmpty()) {
			orderString = " order by t." + pageHelper.getOrderField() + " " + pageHelper.getOrderDirection();
		}
		return orderString;
	}
}
